package com.tenchael.iblog.service.impl;

import com.tenchael.iblog.domain.User;
import com.tenchael.iblog.repository.UserRepository;
import com.tenchael.iblog.service.UserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by tenchael on 25/12/2017.
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

	private static final Logger LOGGER = LogManager.getLogger(UserServiceImpl.class);

	private UserRepository userRepository;

	@Autowired
	public void setUserRepository(UserRepository userRepository) {
		this.userRepository = userRepository;
	}


	@Override
	@Transactional(readOnly = true)
	public User findById(Long id) {
		try {
			return userRepository.getOne(id);
		} catch (Exception e) {
			LOGGER.error("find user by id occurs error", e);
			return null;
		}
	}

	@Override
	public User findByUsername(String username) {
		return userRepository.findByUsername(username);
	}

	@Override
	public User findByEmail(String email) {
		return userRepository.findByUsername(email);
	}

	@Override
	public User findByUsernameOrEmail(String username, String email) {
		return userRepository.findByUsernameOrEmail(username, email);
	}

	@Override
	public User addUser(User user) {
		return userRepository.save(user);
	}
}
